<?php

namespace AdminBundle\Command;

use AdminBundle\Report\TaskFactory;
use AdminBundle\Services\CacheTask;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class TaskReportCommand extends ContainerAwareCommand
{
    private $cacheTask = null;
    private $em = null;
    private $devices = []; // 缓存设备信息

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('task:report:run')
            ->setDescription('tackle report data.');
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $config = $this->getContainer()->getParameter('redis');
        $cacheTask = CacheTask::getInstance($config);
        $em = $this->getContainer()->get('doctrine')->getManager();

        $this->cacheTask = $cacheTask;
        $this->em = $em;

        $ids = [];
        while (1) {
            $output->writeln(microtime(true));

            if (($value = $cacheTask->taskLogPop()) == false) {
                $this->taskBatch($ids, true);
                sleep(5);
                continue;
            }

            $this->taskBatch($ids);

            $task = json_decode($value, true);

            $ids[] = $task['id'];

            if ($task['status'] != 0)
                continue;
            $taskFactory = TaskFactory::create($task['uri']);
            if ($taskFactory == null) {
                continue;
            }
            $device = $this->getDevice($task['device']['imei']);

            $taskFactory->setTask($task)
                ->setIp($task['device']['ip'])
                ->setUsername($task['device']['username'])
                ->setDevice($device)
                ->setDoctrineManager($em);

            $report = $taskFactory->report();

            $output->writeln($report);

            unset($task);
        }
    }

    private function getDevice($imei)
    {
        if (isset($this->devices[$imei])) {
            return $this->devices[$imei];
        }
        $device = $this->em->getRepository('AdminBundle:BaseDevice')->findOneBy(['imei' => $imei]);
        $this->devices[$imei] = $device;
        return $device;
    }

    /**
     * 清空DB中已经处理的数据,
     * @param $ids
     * @return int
     */
    private function taskBatch(&$ids, $force = false)
    {
        $limit = $force ? 1 : 10;
        if (count($ids) < $limit) {
            return 0;
        }

        $this->em->getRepository('AdminBundle:TaskQueueWaiting')->deleteDelivery($ids);
        // 清空已经处理过的数据
        $ids = [];
        return 1;
    }
}
